/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ResultEditor.Display;

import ResultEditor.Annotations.Depot;
import ResultEditor.WorkSpace.WorkSet;
import java.awt.Color;
import java.io.File;
import java.util.ArrayList;
import java.util.Vector;
import javax.swing.JScrollBar;
import javax.swing.JTextPane;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.Document;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;

/**
 *
 * @author Chris
 */
public class Screen {

    protected JTextPane comp;
    protected int latestScrollBarValue;
    protected JScrollBar scollbar;
    protected File textsource;
    protected static int fontsize = 14;

    protected static Vector<Integer> paragraphstartpoints = new Vector<Integer>();

    public Screen(JTextPane comp, File textsource,
            JScrollBar scollbar ){
        this.comp = comp;
        this.scollbar = scollbar;
        this.textsource = textsource;
        // text pane should be set to uneditable
        comp.setEditable(false);  
    }
    
    public Screen(JTextPane comp, File textsource ){
        this.comp = comp;
        this.textsource = textsource;
        // text pane should be set to uneditable
        comp.setEditable(false);  
    }

    public void clearParagraphStartPoints(){
        Screen.paragraphstartpoints.clear();
    }
    
    public void removeAllBackgroundHighLight(){
        AnnotationHighlighter highlighter =  new AnnotationHighlighter(comp);
        highlighter.removeAllPaint();
    }

    /**constractor, only for change font size of document*/
    public Screen(JTextPane comp ){
        this.comp = comp;
        // text pane should be set to uneditable
        comp.setEditable(false);
    }

    /**Show text content and then highlight all these annotations in colorful background.
     * @param contents  An arraylist contains text of each line.
     */
    public void ShowTextAndBackgroundHighLight( ArrayList<String> contents ){
        clearParagraphStartPoints();

        showMonoText( contents );

        highlightAnnotations( comp, textsource );

        ResultEditor.Conflicts.DifferentMatching diff = new
                ResultEditor.Conflicts.DifferentMatching(comp);
        diff.search_differentMatching(textsource);

        comp.setCaretPosition(0);
    }

    
    /**Repaint all high lighter on the text panel for all annotated concepts.*/
    public void repaintHighlight()
    {
        try{
            removeAllBackgroundHighLight();
            highlightAnnotations( comp, textsource );

            ResultEditor.Conflicts.DifferentMatching diff = new
                ResultEditor.Conflicts.DifferentMatching(comp);
            diff.search_differentMatching(textsource);
        }catch(Exception ex){
            System.out.println("error 1102241045:: fail to repaint high lighter"
                    + ex.toString());
        }
    }


    private void setDoclength(ArrayList<String> contents){
        if ( contents == null )
            return;

        int length = 0;
        for( String paragraph : contents ){
            if ( paragraph == null )
                continue;
            length = length + paragraph.length() + 1;
        }
    }

    /**highlight all annotations for this text source*/
    public void highlightAnnotations( JTextPane comp, File textsource )
    {
        try{
            if((comp==null)||(!(comp instanceof JTextPane)))
            {
                System.out.println("error 1102241047-00:: fail to high light annotations.");
                return;
            }

            AnnotationHighlighter highlighter =  new AnnotationHighlighter(comp);

            if (textsource == null)
                return;

            String textsourceFilename = textsource.getName();

            if ((textsourceFilename == null)||(textsourceFilename.trim().length()<1))
                return;

            Vector<Colorblock>  painttasks = paintObjects( textsourceFilename.trim() );

            if ( painttasks == null )   return;

            int size = painttasks.size();
            for(int i=0;i<size;i++){
                Colorblock colorblock = painttasks.get(i);
                if (colorblock == null) continue;
                highlighter.paintColor( colorblock.start, colorblock.end , colorblock.color);
            }
        }catch(Exception ex){
            System.out.println("error 1102241047:: fail to high light annotations."
                    + ex.toString());
        }
    }

    private void showMonoText(ArrayList<String> contents){
        clear();
        if ( contents == null)
            return;

        int size = contents.size();
        int length = 0;
        paragraphstartpoints.add(length);
        for(int i=0;i<size;i++){
            paragraphstartpoints.add(length);
            String line = contents.get(i) + "\n";
            showInTextPane( line );
            setTextStyle(length);
            length = length + line.length();
            
        }
        
        setTextStyle(0);
        
    }

    private void clear(){
        comp.setText(null);
    }

     private void showInTextPane(String _text)  {

        try  {            
            Document doc = comp.getDocument();           
            doc.insertString(doc.getLength(), _text, null);//instert text
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

     public static void setFontSize(int size){
         Screen.fontsize = size;
     }

     private void setTextStyle(int position){
            DefaultStyledDocument doc = (DefaultStyledDocument)comp.getStyledDocument();

            // add this string to end of logs on the Text Pane
            //MutableAttributeSet set = new SimpleAttributeSet();
            // Create and add the main document style
            StyleContext sc = new StyleContext();
            Style defaultStyle = sc.getStyle(StyleContext.DEFAULT_STYLE);

            final Style set = sc.addStyle("set", defaultStyle);
            //StyleConstants.setLineSpacing(set, 2f);
            StyleConstants.setForeground(set, Color.black);
            StyleConstants.setFontFamily(set, "Courier New");
            StyleConstants.setFontSize(set, fontsize );//set size of font
            //set linespace
            StyleConstants.setLineSpacing(set,0.3f);

            doc.setLogicalStyle(position, set);
     }

     public void changeDisplayFontSize(int fontsize){

         setFontSize(fontsize);

         DefaultStyledDocument doc = (DefaultStyledDocument)comp.getStyledDocument();

            // add this string to end of logs on the Text Pane
            //MutableAttributeSet set = new SimpleAttributeSet();
            // Create and add the main document style
            StyleContext sc = new StyleContext();
            Style defaultStyle = sc.getStyle(StyleContext.DEFAULT_STYLE);

            final Style set = sc.addStyle("set", defaultStyle);
            //StyleConstants.setLineSpacing(set, 2f);
            StyleConstants.setFontFamily(set, "Courier New");
            StyleConstants.setFontSize(set, fontsize );//set size of font
            //set linespace
            StyleConstants.setLineSpacing(set,0.3f);

         for( Integer i : Screen.paragraphstartpoints ){
         //this.comp.setFont(new Font( "Courier New", Font.PLAIN, fontsize ));
            doc.setLogicalStyle(i, set);
         }

     }

     class Colorblock{
         int start;
         int end;
         Color color = Color.white; // white is default color
     }

     private Vector<Colorblock> paintObjects(String filename) {
        
        ResultEditor.Annotations.Depot depot = new ResultEditor.Annotations.Depot();         
        final ResultEditor.Annotations.Article article = Depot.getArticleByFilename( filename );
        if ( article == null )  return null;

        Vector<ResultEditor.Annotations.Annotation> annotations = article.annotations;
        if ( annotations == null )  return null;

        Vector<Colorblock> colorblocks = new Vector<Colorblock>();

        int size = annotations.size();

        // to each imported annotation, check and pick out these who are
        // in range of current paragraph
        try {
            for (int i = 0; i < size; i++) {
                if(WorkSet.filteredViewing) {
                    if(!WorkSet.currentlyViewing.contains(i))
                        continue;
                }
                ResultEditor.Annotations.Annotation annotation = annotations.get(i);
                //if(validIndices != null) {
                //    if(!validIndices.contains(i))
                //        continue;
                //}
                if ( !annotation.visible )  continue;

                Colorblock colorblock = new Colorblock();
                colorblock.start = annotation.spanstart;
                colorblock.end = annotation.spanend;
                String className = annotation.annotationclass.trim();
                //System.out.println(" - classname = [" + className + "]");
                Color c = ResultEditor.AnnotationClasses.Depot.getColor( className );
                if (c == null)  c = Color.BLACK;
                
                colorblock.color = c;

                colorblocks.add(colorblock);

            }
        } catch (Exception e) {
            Logs.ShowLogs.printErrorLog("gui.java - paintline() - error2752" + e.toString());
        }

        return colorblocks;
    }
}
